package com.chuangjiangx.member.basic.web.controller;

import com.chuangjiangx.commons.exception.BaseException;
import com.chuangjiangx.commons.response.CamelResponse;
import com.chuangjiangx.commons.response.Response;
import com.chuangjiangx.commons.response.ResponseUtils;
import com.chuangjiangx.commons.wx.auth.WXWebAuthType;
import com.chuangjiangx.domain.shared.model.BrowserType;
import com.chuangjiangx.member.basic.ddd.application.EntryApplication;
import com.chuangjiangx.member.basic.ddd.application.LoginApplication;
import com.chuangjiangx.member.basic.ddd.application.MemberApplication;
import com.chuangjiangx.member.basic.ddd.domain.model.WxAppletTokenRepository;
import com.chuangjiangx.member.basic.ddd.domain.model.MbrUserMapping;
import com.chuangjiangx.member.basic.ddd.domain.model.MbrUserMappingRepository;
import com.chuangjiangx.member.basic.ddd.domain.model.Member;
import com.chuangjiangx.member.basic.ddd.domain.model.MemberRepository;
import com.chuangjiangx.member.basic.ddd.domain.service.model.MemberLogin;
import com.chuangjiangx.member.common.BrowserTypeConstant;
import com.chuangjiangx.member.basic.web.interceptor.Login;
import com.chuangjiangx.member.basic.web.request.LoginRequest;
import com.chuangjiangx.member.coupon.web.response.response.LoginStatusResponse;
import com.chuangjiangx.member.basic.web.response.MemberLoginResponse;
import com.chuangjiangx.member.basic.ddd.query.MemberQuery;
import com.chuangjiangx.member.basic.ddd.query.MerchantUserInfoQuery;
import com.chuangjiangx.member.basic.ddd.query.dto.MemberDTO;
import com.chuangjiangx.member.basic.ddd.query.dto.MerchantUserDTO;
import com.chuangjiangx.member.basic.ddd.domain.model.MbrUserContext;
import com.chuangjiangx.member.basic.ddd.domain.model.MbrUserMappingType;
import com.chuangjiangx.publicmodule.domain.upload.service.UploadFileService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * H5页面会员登录
 */
@Slf4j
@RestController
@RequestMapping(value = "/h5")
@Api(value = "登录", tags = "入口")
public class LoginController extends BaseController {


    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private MemberApplication memberApplication;

    @Autowired
    private MerchantUserInfoQuery merchantUserInfoQuery;

    @Autowired
    private MemberQuery memberQuery;
    @Autowired
    private LoginApplication loginApplication;
    @Autowired
    private WxAppletTokenRepository wxAppletTokenRepository;

    @Autowired
    private UploadFileService uploadFileService;
    @Autowired
    private MemberRepository memberRepository;
    @Autowired
    private EntryApplication entryApplication;
    @Autowired
    private MbrUserMappingRepository mbrUserMappingRepository;


    /**
     * 登录会员系统 微信中通过授权连接跳转到登录页登录\普通浏览器手机号+验证码登录
     *
     * @param loginRequest 登录请求参数
     * @return com.chuangjiangx.commons.response.GenericResponse
     * @see MemberLoginResponse
     */
    @ApiOperation(value = "登录会员中心", httpMethod = "POST", notes = "登录会员中心notes")
    @RequestMapping(value = "/login")
    public CamelResponse<MemberLoginResponse> memberLogin(HttpServletRequest request, @RequestBody LoginRequest loginRequest) throws Exception {

        //验证码验证
        if (!checkVerifyCode(loginRequest)) {
            return (CamelResponse<MemberLoginResponse>) ResponseUtils.errorCamel("", "验证错误");
        }
        /**
         * 考虑两种情况
         * 1.手机号+商户Id+服务商openid+商户公众号openid
         * 2.普通浏览器登录,只有手机号和商户Id
         */
        MemberLoginResponse response = new MemberLoginResponse();
        MbrUserContext userContext = loginService.currentUserContext();
        BrowserType browserType = BrowserType.ofUA(request.getHeader("User-Agent"));
        if (browserType.getName().equals(BrowserTypeConstant.BROWSER_WX_PAY)) {
            // 微信通过授权连接登录,这个时候有openid
            // 如果手机号码不是会员需要自动注册
            // 需要判断openid是否和会员是否绑定,是否正确绑定
             wxLogin(userContext, loginRequest.getMobile(), response);
        } else {
            // 普通浏览器登录,只有手机号和商户Id
            // 如果不是会员需要自动注册
            otherBrowsers(loginRequest.getMobile());
        }
        return (CamelResponse<MemberLoginResponse>) ResponseUtils.successCamel(response);
    }

    /**
     * 浏览器登录
     * @param mobile
     * @return
     */
    private void otherBrowsers(String mobile) {
        //loginInfo 逻辑上不会为空
        MbrUserContext userContext = loginService.currentUserContext();
        //查询会员
        MemberDTO dto = memberQuery.queryByMerchantAndMobile(userContext.getMerchantId(), mobile);
        if (dto == null) {
            //自动注册
            throw new BaseException("", "暂不支持非微信浏览器自动注册");
        } else {
            userContext.setMobile(dto.getMobile());
            userContext.setMemberId(dto.getId());
            userContext.setName(dto.getName());
            userContext.setSex(dto.getSex());
            userContext.setMerchantId(dto.getMerchantId());
            userContext.setMerchantUserId(dto.getRegisterMerchantUserId());
        }
        if (null == userContext.getMerchantUserId()) {
            userContext.setMerchantUserId(merchantUserInfoQuery.getDefaultMerchantUserId(userContext.getMerchantId()));
        }
        loginService.saveUserContext(userContext);
    }

    /**
     * 微信中登录
     */
    private void wxLogin(MbrUserContext userContext, String mobile, MemberLoginResponse response) {
        userContext.setMobile(mobile);
        userContext.setMbrUserMappingType(MbrUserMappingType.WX);
        MemberLogin memberLogin = loginApplication.wxLogin(userContext);
        Member member = memberLogin.getMember();
        userContext.setMobile(member.getMobile());
        userContext.setMemberId(member.getId().getId());
        userContext.setName(member.getName());
        //登录成功后都是正式会员了
        userContext.setState(MbrUserContext.State.MEMBER);
        if(null == userContext.getMerchantUserId()){
            userContext.setMerchantUserId(merchantUserInfoQuery.getDefaultMerchantUserId(userContext.getMerchantId()));
        }
        loginService.updateUserContext(userContext);

//        if (redisTemplate.hasKey(RedisKeyManager.MBR_H5_LABEL + userContext.getOpenId() + userContext.getMerchantId())) {
//            response.setFromVip(true);
//        } else {
//            String key = RedisKeyManager.MBR_H5_LABEL + "JOIN_MEMBER_" + userContext.getOpenId() + userContext.getMerchantId();
//            if (redisTemplate.hasKey(key)) {
//                response.setFromUrl(redisTemplate.opsForValue().get(key));
//                redisTemplate.delete(key);
//            }
//        }
        //赠送的卡券
        response.setMbrHasCouponId(memberLogin.getMbrHasCouponId());

        //一定是微信的映射关系---后端优化
        MbrUserMapping mbrUserMapping = memberLogin.getMbrUserMapping();
        if(StringUtils.isBlank(mbrUserMapping.getMopenId())){
            //没有商户公众号的openid需要重定向获取
            response.setState(1);
            response.setRedirectUrl(entryApplication.merchantWxWebAuthUrl(userContext.getMerchantId(),WXWebAuthType.USERINFO));
        }
    }

    /**
     * 登出会员系统
     *
     * @return com.chuangjiangx.commons.response.UnderlineResponse
     */
    @ApiOperation(value = "会员注销登录接口",httpMethod = "GET")
    @RequestMapping(value = "/logout")
    @Login
    public Response logout() throws Exception {
        loginService.loginOut();
        return ResponseUtils.successCamel();
    }

    /**
     * 获取商户用户id
     *
     * @param merchantId 商户id
     * @return 商户用户id
     */
    private Long queryMerchantUserIdByMerchantId(Long merchantId) throws Exception {

        List<MerchantUserDTO> dtoList = merchantUserInfoQuery.searchMerchantUserByMerchantId(merchantId);

        if (dtoList != null && dtoList.size() > 0) {
            return dtoList.get(0).getId();
        }
        throw new BaseException("000001", "获取商户用户信息失败");
    }



    @ApiOperation(value = "获取用户登录状态",httpMethod = "GET")
    @RequestMapping(value = "/login-status",method = RequestMethod.GET)
    public CamelResponse<LoginStatusResponse> isLogin(
            @RequestParam Long merchantId
    ) {
        LoginStatusResponse statusResponse = new LoginStatusResponse();
        MbrUserContext userContext = loginService.currentUserContext();
        if(null != userContext){
            if(isValidLogin(userContext,merchantId)){
                statusResponse.setLogin(true);
                statusResponse.setMobile(userContext.getMobile());
            }
        }
        return (CamelResponse<LoginStatusResponse>)ResponseUtils.successCamel(statusResponse);

    }


}
